<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/14
 * Time: 18:13
 */

namespace app\admin\controller;


use app\admin\lib\AdminController;
use app\common\model\teacher\Teacher;
use app\common\model\teacher\TeacherSpeaking;
use app\admin\model\ApiResponse;
use app\common\utils\OssUtil;
use think\Db;

class Speaking extends AdminController
{
    /**
     * @return \app\admin\model\PageResponse
     */
    public function list() {
        $form = $this->getAndCheckForm([
            ['limit', 'require',],
            ['offset', 'require',],
        ]);
        
        $page = TeacherSpeaking::manageList(intval($form['limit']), intval($form['offset']), ($form['keywords'] ?? null));
        return $page;
    }

    /**
     * @return ApiResponse
     */
    public function save() {
        Db::transaction(function(){
            $form = $this->getAndCheckForm([
                ['teacher_id', 'require|integer',],
                ['title', 'require',],
                ['url', 'require',],
            ]);
            $id = intval($form['id'] ?? 0);
            if ($id > 0) {
                TeacherSpeaking::update($form);
            } else {
                TeacherSpeaking::create($form);
                Teacher::countNumSpeaking($form['teacher_id']);
            }
        });
        return ApiResponse::success();
    }

    public function del() {
        $form = $this->getAndCheckForm([
            ['id', 'require',],
        ]);
        $id = intval($form['id']);
        if ($id > 0) {
            $speaking = TeacherSpeaking::get($id);
            OssUtil::delete($speaking->url);
            $speaking->delete();
            Teacher::countNumSpeaking($speaking->teacher_id);
        }

        return ApiResponse::success();
    }

}